package com.crl.rcdp.gateway.filter;

import com.cars.util.global.GlobalReturnCode;
import com.cars.util.json.JsonResult;
import com.cars.util.json.JsonUtil;
import com.cars.util.log.LogUtil;
import com.cars.util.string.StringUtil;
import com.crl.rcdp.sys.model.SysErrorLog;
import com.crl.rcdp.sys.service.SysErrorLogService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.crossstore.ChangeSetPersister;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/8/17 23:23
 */
public class ErrorFilter extends ZuulFilter {
    @Autowired
    private SysErrorLogService sysErrorLogService;

    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Throwable ex = ctx.getThrowable();
//        log.error("this is a ErrorFilter :" + throwable.getCause().getMessage(), throwable);
        ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        ctx.set("error.exception", ex.getCause());
        JsonResult jsonResult = null;
        String bodyMsg = "";
        HttpStatus httpStatus;
        ex.printStackTrace();
        if (ex instanceof ChangeSetPersister.NotFoundException) {
            httpStatus = HttpStatus.NOT_FOUND;
            bodyMsg = "Service Not Found";
            jsonResult = new JsonResult(GlobalReturnCode.URI_NOT_FOUND);
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            httpStatus = responseStatusException.getStatus();
            bodyMsg = responseStatusException.getMessage();
            if (responseStatusException.getStatus().value() == 404) {
                jsonResult = new JsonResult(GlobalReturnCode.URI_NOT_FOUND);
            } else {
                jsonResult = new JsonResult(GlobalReturnCode.SERVER_ERROR);
            }
        } else {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
            bodyMsg = "Internal Server Error";
            jsonResult = new JsonResult(GlobalReturnCode.SERVER_ERROR);
        }

        //记录异常至数据库
        SysErrorLog sysLog = new SysErrorLog();
        String servletPath = request.getServletPath();//获取请求url
        String authorization = request.getHeader("Authorization");//获取authorization
        String appid = request.getHeader("appid");//appid
        String accessToken = request.getHeader("accessToken");//accessToken
        sysLog.setClientIp(StringUtil.getIp(request));//ip地址
        sysLog.setAuthType(FilterUtil.getAuthType(authorization, accessToken, appid));//授权方式
        sysLog.setPath(servletPath);//请求地址
        sysLog.setRequestParam("");//请求参数
        sysLog.setOwner(FilterUtil.getOwner(authorization, accessToken, appid));//owner
        sysLog.setResponse(JsonUtil.toStr(jsonResult));//返回值
        LogUtil.error("sysLog", sysLog.toString());
        sysErrorLogService.add(sysLog);
        StringUtil.out(ctx.getResponse(), JsonUtil.toStr(jsonResult));
        return null;
    }

}
